#! /usr/bin/env python
# -*- coding: utf-8 -*-

import time
import os
import re
import random
import pycurl
import StringIO

import FileHostProtoType


class sobitem(FileHostProtoType.HostItem):
    def __init__(self, name, type, code, link='', encrypt_name='', server_name=''):
        FileHostProtoType.HostItem.__init__(self, name, type, code, link, encrypt_name, server_name)
    
class shareonlinebiz(FileHostProtoType.FileHostProcess):            
    def __init__(self, user, pwd):
        FileHostProtoType.FileHostProcess.__init__(self)
        self.hostname = "Share-Online.biz" 
        self._opener = None
        self._user = user
        self._pwd = pwd
        self.islogin = False
        self.logtype = 'poster'

            
    def login(self):
        if self.islogin:
            return True
        #build opener
        self.generateOpener()
        self.fherr.write('login to Share-Online.biz %s/%s...'%(self._user,'*'*len(self._pwd)))
        loginData = {'user' : self._user, \
                'pass' : self._pwd}
        response = self.loginFileHost("https://www.share-online.biz/user/login", loginData)
        
        user_config_page = self.post_request("https://www.share-online.biz/user/config")
        # user info can be found in cookie
        if self._user.lower() not in user_config_page.lower():
            self.fherr.write("User %s Failed to Login DepositFiles." % self._user)
            return False
        self.fherr.write("User %s logined." % self._user)
        self.islogin = True
        return True
        
    def getFileList(self):
        return []
    
    def upload_web(self, file, progressLog=None, other_args=None, send_range=None):
        #indexpage        
        get_upload_info_url = 'http://www.share-online.biz/upv3_session.php'
        data = {'username':self._user,
                'password':self._pwd}
        get_upload_info_page = self.post_request(get_upload_info_url, data)
        
        #print get_upload_info_page
        tokens = get_upload_info_page.split(';')
        if len(tokens) != 2:
            self.fherr.write("Failed to get session and upload url.")
            return        
        srv_tmp_url = tokens[1]
        sess_id = tokens[0]
        upload_url = "http://{}".format(srv_tmp_url)        
        
        info = "Uploading...%s" % file
        filesize = os.path.getsize(file)
        filename = self.rename_func(file)
        start_point = 0
        if send_range is not None:
            #range is a 3-tuple, <start, end, number>
            filesize = send_range[1] - send_range[0] + 1
            filename += ".%03d" % send_range[2]
            start_point = send_range[0]
            info += " part%d" % send_range[2]
            
        fileobj = open(file, 'rb')
        fileobj.seek(start_point)  
        
        data = {"username":self._user,
                "password":self._pwd,
                "upload_session":sess_id,
                "chunk_no":"1",
                "chunk_number":"1",
                "filesize":filesize,
                "finalize":'1',
                "fn":fileobj}
        
        self.fherr.write(info)
        
        callback = None
        if progressLog is not None:
            callback = progressLog.write
        result = self.post_request(upload_url, \
                                   data, \
                                   cb=callback, \
                                   retry=1, \
                                   setfilename=filename, \
                                   setfilesize=filesize)
        #result
        #print result
        tokens = result.split(';')
        if len(tokens) != 3:
            self.fherr.write("Get a wrong result after uploaded.")
            self.fherr.write(result)
            return
        link = tokens[0]+"#"+filename
        item = sobitem(os.path.basename(file), 'file', '', link, filename)
        self.newupload.append(item)
        self.fhout.write(item.format()) 
        return item